import { copyText } from '../../utils/utils'
import { TMessage } from '../../directive/TMessage/globalMessage'
import type { Directive, DirectiveBinding } from 'vue'

export type VCopy = Directive<HTMLElement, string>

const handleClick = (binding: DirectiveBinding) => {
  return () => {
    try {
      copyText(binding.value)
      TMessage.success('复制成功')
    } catch {
      TMessage.warning('复制失败')
    }
  }
}

const vCopy: VCopy = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    el.addEventListener('click', handleClick(binding))
  },
  beforeUnmount(el: HTMLElement, binding: DirectiveBinding) {
    el.removeEventListener('click', handleClick(binding))
  }
}

export default vCopy
